package com.asset.dispoal.channel.service.common;

import com.asset.dispoal.channel.domain.db.entity.SysChannelOpen;
import com.asset.dispoal.channel.domain.db.mapper.SysChannelMapper;
import com.asset.dispoal.channel.dto.SysChannelOpenRequest;
import com.asset.dispoal.channel.service.converter.SysChannelConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.date.DateTimeUtil;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.math.BigDecimal;

/**
 * @author qr
 * @date 2022/3/25$
 */
@Component
public class SysChannelOpenUpdateCommand implements BaseCommand<SysChannelOpenRequest, Result> {

    @Autowired
    SysChannelMapper sysChannelMapper;

    @Override
    public Result execute(SysChannelOpenRequest request) {
        SysChannelOpen open = sysChannelMapper.getByOpenId(request.getId());
        SysChannelOpen sysChannelDebt = SysChannelConverter.INSTANCE.resOpenToDo(request);
        sysChannelDebt.setSurplus(request.getMoney().subtract(open.getMoney()).add(open.getSurplus()));
        sysChannelDebt.setCreateTime(DateTimeUtil.currentDate());
        sysChannelDebt.setUpdateTime(DateTimeUtil.currentDate());
        sysChannelMapper.updateOpen(sysChannelDebt);
        if("1".equals(sysChannelDebt.getChecked())){
            if("1".equals(open.getChecked())){
                sysChannelMapper.addOpenMoney(request.getMoney().subtract(open.getMoney()),
                        sysChannelDebt.getChannelId());
            }else{
                sysChannelMapper.addOpenMoney(request.getMoney(),sysChannelDebt.getChannelId());
            }
        }else{
            if("1".equals(open.getChecked())){
                sysChannelMapper.addOpenMoney(BigDecimal.ZERO.subtract(open.getMoney()),
                        sysChannelDebt.getChannelId());
            }
        }
        return Result.ok();
    }
}
